<template>
  <view v-if="visible" class="share-modal" @click="handleMaskClick">
    <view class="share-content" @click.stop>
      <!-- Canvas绘制的海报 -->
      <view class="canvas-container">
        <canvas 
          id="posterCanvas"
          canvas-id="posterCanvas" 
          :style="{width: canvasWidth + 'px', height: canvasHeight + 'px'}"
          class="poster-canvas"
        ></canvas>
        <!-- 右上角关闭按钮 -->
        <view class="canvas-close-btn" @click="close">
          <text class="canvas-close-text">×</text>
        </view>
      </view>
      
      <!-- 底部按钮 -->
      <view class="bottom-buttons">
        <view class="button-wrapper" @click="saveImage">
          <button class="button-item" >
            <image class="button-icon"  mode="widthFix" src="https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/share/download@2x.png" />
            <text class="button-text">保存图片</text>
          </button>
        </view>
        <view class="button-wrapper">
          <button class="share-button" open-type="share">
            <image class="share-button-icon" mode="widthFix" src="https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/share/wechat@2x.png" />

            <text class="button-text">分享好友</text>
          </button>
        </view>
      </view>
    </view>
    
    <!-- 关闭按钮 -->
    <view class="close-btn" @click="close">
      <text class="close-text">×</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch, nextTick, getCurrentInstance } from 'vue';
import { HomeApi } from '@/api/index.js';
import LoginUtils from '@/utils/loginUtils.js';

// 获取当前组件实例
const instance = getCurrentInstance();

// 定义 props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  type: {
    type: Number,
    default: 1 // 1: activity, 2: parking
  },
  userId: {
    type: String,
    default: ''
  }
});

// 定义 emits
const emit = defineEmits(['close']);

// Canvas相关数据
const canvasWidth = ref(300);
const canvasHeight = ref(510); // 调整高度以适应200x200二维码和底部文字区域
const canvasContext = ref(null);
const backgroundImage = ref(null);
const qrCodeImage = ref(null);
const qrCodeData = ref(''); // 二维码数据，通过API获取的byte流
const channel = LoginUtils.getChannel();

// 获取二维码数据
const getQrCodeData = async () => {
  try {
    // 根据类型确定分享页面和参数
    const page = props.type === 1 ? 'activity' : 'parking';
    const param = props.userId;

    const data = await HomeApi.getSharePage(page, param, channel);
    
    // 处理API返回的数据
    if (data) {
      qrCodeData.value = data;

      console.log('获取到的二维码图片地址:', qrCodeData.value);
    } else {
      console.error('API返回的数据为空');
      qrCodeData.value = '';
    }

  } catch (error) {
    console.error('获取二维码失败:', error);
    qrCodeData.value = '';
  }
};

const backgroundImageUrl = computed(() => {
  return props.type === 1 
    ? 'https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/share/poster%402x.png'
    : 'https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/poster.png'; // 可以为不同类型设置不同背景
});

// 监听visible变化，当显示时先获取二维码再绘制Canvas
watch(() => props.visible, async (newVal) => {
  if (newVal) {
    await getQrCodeData(); // 先获取二维码数据
    // nextTick(() => {
      initCanvas();
    // });
  }
});

// 初始化Canvas
const initCanvas = () => {
  // 支付宝小程序需要特殊处理
  canvasContext.value = channel === 0 ? uni.createCanvasContext('posterCanvas') : uni.createCanvasContext('posterCanvas', instance);

  
  loadImages();
};

// 加载图片资源
const loadImages = () => {
  let loadedCount = 0;
  const totalImages = 2;
  
  // 加载背景图
  const loadBackgroundImage = () => {
    // 支付宝小程序可能需要特殊处理
    console.log('支付宝小程序加载背景图:', backgroundImageUrl.value);

    uni.getImageInfo({
      src: backgroundImageUrl.value,
      success: (res) => {
        console.log('背景图加载成功:', res);
        backgroundImage.value = res;
        loadedCount++;
        if (loadedCount === totalImages) {
          drawPoster();
        }
      },
      fail: (err) => {
        console.error('背景图加载失败:', err);
        console.error('失败的背景图URL:', backgroundImageUrl.value);
        loadedCount++;
        if (loadedCount === totalImages) {
          drawPoster();
        }
      }
    });
  };
  
  loadBackgroundImage();
  
  // 处理二维码数据
  const loadQrCodeImage = () => {
    if (qrCodeData.value) {
      console.log('加载二维码图片地址:', qrCodeData.value);

      uni.getImageInfo({
        src: qrCodeData.value,
        success: (res) => {
          console.log('二维码加载成功:', res);
          qrCodeImage.value = res;
          loadedCount++;
          if (loadedCount === totalImages) {
            drawPoster();
          }
        },
        fail: (err) => {
          console.error('二维码加载失败:', err);
          console.error('失败的图片地址:', qrCodeData.value);
          console.error('错误详情:', JSON.stringify(err));
          loadedCount++;
          if (loadedCount === totalImages) {
            drawPoster();
          }
        }
      });
    } else {
      console.log('二维码数据为空，跳过加载');
      loadedCount++;
      if (loadedCount === totalImages) {
        drawPoster();
      }
    }
  };
  
  loadQrCodeImage();
};

// 绘制海报
const drawPoster = () => {
  const ctx = canvasContext.value;
  console.log(ctx);
  if (!ctx) {
    console.error('Canvas上下文不存在');
    return;
  };
  console.log('开始绘制');

  // 清空画布
  ctx.clearRect(0, 0, canvasWidth.value, canvasHeight.value);
  ctx.scale(1, 1)
  
  // 绘制背景
  ctx.setFillStyle('#ffffff');
  ctx.fillRect(0, 0, canvasWidth.value, canvasHeight.value);
  
  // 绘制背景图
  let backgroundHeight = 350; // 默认背景高度
  if (backgroundImage.value) {
    const imgWidth = backgroundImage.value.width;
    const imgHeight = backgroundImage.value.height;
    const canvasW = canvasWidth.value;
    
    // 计算保持宽高比的高度
    const aspectRatio = imgHeight / imgWidth;
    backgroundHeight = canvasW * aspectRatio;
    
    // 绘制背景图，宽度占满，高度按比例计算
    ctx.drawImage(backgroundImage.value.path, 0, 0, canvasW, backgroundHeight);
  }
  
  // 绘制type=2时的文字内容
  if (props.type === 2) {
    ctx.setTextAlign('center');
    ctx.setFillStyle('#ffffff');
    
    // 标题
    ctx.setFontSize(18);
    ctx.fillText('某某邀请你办理停车包月', canvasWidth.value / 2, backgroundHeight * 0.4);
    
    // 副标题
    ctx.setFontSize(16);
    ctx.fillText('某某停车场名称', canvasWidth.value / 2, backgroundHeight * 0.5);
    
    ctx.setFontSize(14);
    ctx.fillText('可在线办理停车月卡啦', canvasWidth.value / 2, backgroundHeight * 0.6);
    
    // 价格
    ctx.setFontSize(24);
    ctx.fillText('¥50/月', canvasWidth.value / 2, backgroundHeight * 0.75);
    
    ctx.setFontSize(12);
    ctx.fillText('原价¥80/月', canvasWidth.value / 2, backgroundHeight * 0.85);
  }
  
  // 绘制二维码背景，位置在背景图内的预留区域
  const qrSize = 142; // 二维码尺寸200x200
  const qrX = (canvasWidth.value - qrSize) / 2;
  const qrY = 270; 
  const borderRadius = 10; // 圆角半径
  
  // 绘制圆角背景
  ctx.setFillStyle('#ffffff');
  ctx.beginPath();
  ctx.moveTo(qrX - 5 + borderRadius, qrY - 5);
  ctx.lineTo(qrX - 5 + qrSize + 10 - borderRadius, qrY - 5);
  ctx.quadraticCurveTo(qrX - 5 + qrSize + 10, qrY - 5, qrX - 5 + qrSize + 10, qrY - 5 + borderRadius);
  ctx.lineTo(qrX - 5 + qrSize + 10, qrY - 5 + qrSize + 10 - borderRadius);
  ctx.quadraticCurveTo(qrX - 5 + qrSize + 10, qrY - 5 + qrSize + 10, qrX - 5 + qrSize + 10 - borderRadius, qrY - 5 + qrSize + 10);
  ctx.lineTo(qrX - 5 + borderRadius, qrY - 5 + qrSize + 10);
  ctx.quadraticCurveTo(qrX - 5, qrY - 5 + qrSize + 10, qrX - 5, qrY - 5 + qrSize + 10 - borderRadius);
  ctx.lineTo(qrX - 5, qrY - 5 + borderRadius);
  ctx.quadraticCurveTo(qrX - 5, qrY - 5, qrX - 5 + borderRadius, qrY - 5);
  ctx.closePath();
  ctx.fill();
  
  // 绘制圆角边框
  ctx.setStrokeStyle('#1CCCB4');
  ctx.setLineWidth(1);
  ctx.stroke();
  
  // 绘制二维码（处理byte流数据）
  if (qrCodeData.value && qrCodeImage.value) {
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(qrX + borderRadius, qrY);
    ctx.lineTo(qrX + qrSize - borderRadius, qrY);
    ctx.quadraticCurveTo(qrX + qrSize, qrY, qrX + qrSize, qrY + borderRadius);
    ctx.lineTo(qrX + qrSize, qrY + qrSize - borderRadius);
    ctx.quadraticCurveTo(qrX + qrSize, qrY + qrSize, qrX + qrSize - borderRadius, qrY + qrSize);
    ctx.lineTo(qrX + borderRadius, qrY + qrSize);
    ctx.quadraticCurveTo(qrX, qrY + qrSize, qrX, qrY + qrSize - borderRadius);
    ctx.lineTo(qrX, qrY + borderRadius);
    ctx.quadraticCurveTo(qrX, qrY, qrX + borderRadius, qrY);
    ctx.closePath();
    ctx.clip();
    ctx.drawImage(qrCodeImage.value.path, qrX, qrY, qrSize, qrSize);
    ctx.restore();
  }
  
  // 绘制底部文字区域背景，位置在背景图内的预留区域
  const textY = 440; // 调整位置以适应200x200的二维码
  ctx.setFillStyle('#E7FFFC');
  ctx.fillRect(20, textY, canvasWidth.value - 40, 50);
  
  // 绘制文字
  ctx.setTextAlign('center');
  ctx.setFillStyle('#09D5A9');
  ctx.setFontSize(16);
  ctx.fillText('扫码即可申请', canvasWidth.value / 2, textY + 20);
  
  ctx.setFillStyle('#666666');
  ctx.setFontSize(14);
  const descText = props.type === 1 ? '每个小区仅限申请20台' : '点击在线包月，立享即生效';
  ctx.fillText(descText, canvasWidth.value / 2, textY + 40);
  
  // 执行绘制
  
   setTimeout(() => {
    ctx.draw(true, () => {
      console.log('Canvas绘制完成回调触发');
    });
  }, 100)

    console.log('绘制完毕');

};

// 方法
const close = () => {
  emit('close');
};

const handleMaskClick = () => {
  close();
};

const saveImage = () => {
  // 使用canvasToTempFilePath保存图片
  const canvasOptions = {
    canvasId: 'posterCanvas',
    success: (res) => {
      console.log(res)
      // 保存到相册
      uni.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success: () => {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
        },
        fail: (err) => {
          console.error('保存失败:', err);
          uni.showToast({
            title: '保存失败',
            icon: 'none'
          });
        }
      });
    },
    fail: (err) => {
      console.error('生成图片失败:', err);
      uni.showToast({
        title: '生成图片失败',
        icon: 'none'
      });
    }
  };
  
  // 支付宝小程序不需要instance参数
  if (channel.value === 0){
    uni.canvasToTempFilePath(canvasOptions);
  }else{
    uni.canvasToTempFilePath(canvasOptions, instance);
  }
};


</script>

<style scoped>
.share-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.share-content {
  position: relative;
  width: 300px;
  padding-top: 200rpx;
}

.canvas-container {
  position: relative;
}

.share-card {
  position: relative;
  background-color: #ffffff;
  /* border-radius: 12px; */
  overflow: hidden;
  margin-bottom: 20px;
}

.card-header {
  height: 350px;
  position: relative;
  background-size: cover;
  background-position: top;
  background-repeat: no-repeat;
}

/*.header-activity {*/
/*  background-image: url('https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/poster.png');*/
/*}*/



.header-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #ffffff;
}

.title {
  font-size: 18px;
  font-weight: bold;
  display: block;
  margin-bottom: 8px;
}

.subtitle {
  font-size: 16px;
  display: block;
  margin-bottom: 4px;
}

.subtitle2 {
  font-size: 14px;
  display: block;
  margin-bottom: 12px;
}

.price {
  font-size: 24px;
  font-weight: bold;
  display: block;
  margin-bottom: 4px;
}

.original-price {
  font-size: 12px;
  opacity: 0.8;
  display: block;
}

.qr-code-overlay {
  position: absolute;
  bottom: -80px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
}

.qr-text-section {
  padding: 100px 20px 30px;
  text-align: center;
}

.qr-text-block {
  /* display: inline-block; */
  background: #E7FFFC;
  border-radius: 11px;
  padding: 12px 20px;
}

.qr-code {
  width: 140px;
  height: 128px;
  background: #FFFFFF;
  border-radius: 10px;
  border: 1px solid #1CCCB4;
  padding: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.qr-image {
  width: 100%;
  height: 100%;
}

.qr-text {
  font-size: 16px;
  color: #09D5A9;
  font-weight: bold;
  display: block;
  margin-bottom: 8px;
}

.qr-desc {
  font-size: 14px;
  color: #666666;
  display: block;
}

.bottom-buttons {
  display: flex;
  justify-content: space-around;
  /* background-color: rgba(255, 255, 255, 0.9); */
  border-radius: 25px;
  padding: 5px;
}

.button-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 20px;
}

.button-item {
  background: none;
  border: none;
  outline: none;
  padding: 0;
  margin-top: 8px;
  display: flex;
  flex-direction: column;
  height: 90px;
}

.share-button {
  background: none;
  border: none;
  outline: none;
  padding: 0;
  margin-top: 8px;
  display: flex;
  flex-direction: column;
  height: 90px;
}
.share-button-icon {
  width: 45px;
  height: 45px;
  /* margin-bottom: 8px; */
}
.button-icon {
  width: 45px;
  height: 45px;
  /* margin-bottom: 8px; */
}

.button-text {
  font-size: 14px;
  color: #FFFFFF;
  opacity: 0.8;
}

.close-btn {
  position: absolute;
  top: -50px;
  right: 10px;
  width: 32px;
  height: 32px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.close-text {
  font-size: 20px;
  color: #666666;
  font-weight: bold;
}

.card-close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 28px;
  height: 28px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.card-close-text {
  font-size: 16px;
  color: #FFFFFF;
  font-weight: bold;
}

.canvas-close-btn {
  position: absolute;
  top: -30px;
  right: 10px;
  width: 24px;
  height: 24px;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.canvas-close-text {
  font-size: 22px;
  color: #FFFFFF;
  opacity: 0.9;
  /* font-weight: bold; */
}
</style>